<?php

namespace app\common\service\coupon;

use app\common\facade\auth\Auth;
use app\common\service\auth\AuthOpenService;
use app\model\ChannelServDiscount;
use app\model\CouponBrand;
use app\model\CouponProductChannel;
use app\Query;

class CouponBrandService
{
    /**
     * 有效的所有品牌
     */
    public function effectiveBrand(){


        $auth = Auth::instance();

        $trueServers = (new ChannelServDiscount())->getRealServ(Auth::channelId(), Auth::agentId());

        $brands = CouponBrand::query()
            ->field(['*','coupon_brand_cate_relation.cate_id as cat_id'])
            ->alias('CouponBrand')
            ->with(['productChannel' => function($query) {
                $query->availableSale();
            }])
            ->where(function ($query) use ($trueServers) {
                /**
                 * @var Query $query
                 */
                $query->whereRaw('EXISTS(SELECT * FROM coupon_product_channel WHERE brand_id = `CouponBrand`.`id` 
                    and `status` = ' . CouponProductChannel::STATUS_ACTIVE . '
                    and butt = ' . CouponProductChannel::BUTT_ACTIVE . ' 
                    and sku_type = ' . CouponProductChannel::SKU_TYPE_ZC . ' 
                    and relate_state = ' . CouponProductChannel::RELETE_STATE_YPP . '
                    and shelf_state = ' . CouponProductChannel::RELETE_STATE_YPP . '
                     )')
                    ->whereOr(function ($query)use($trueServers){
                        $query->where([
                            ['belong', '=', CouponBrand::BELONG_JUTUIKE],
                            ['serv_type', 'in', $trueServers],
                        ]);
                    });
            })
            ->join('coupon_brand_cate_relation', 'coupon_brand_cate_relation.brand_id = coupon_brand.id')
//                ->where('coupon_brand_cate_relation.cate_id', $data['id'])
            ->where('coupon_brand.status', CouponBrand::STATUS_ACTIVE)
            ->order('coupon_brand.sort desc, coupon_brand.updated_at desc')
            ->select()->each(function (CouponBrand $couponBrand) use ($auth) {
                if (!$auth instanceof AuthOpenService) {
                    if ($couponBrand->belong == CouponBrand::BELONG_HUICHONG) {
                        $couponBrand->productChannelObj = $couponBrand->productChannel;
                        $couponBrand->append(['sale_price_discount']);
                    }
                }
            })
            ->toArray();

          return $brands;

    }
}